﻿$(document).ready(
	function () {

		$.each($('#control_panel .action'), function () {
			var text = $(this).text().trim();
			if (text == '关注') {
				if (oVoc.isfollow == true) {
					$(this).text('已关注');
					$(this).removeClass('follow').addClass('followed').attr('title', '点击取消关注');
				}
				$(this).bind("click", { fun: Follow, title: "", argus: { vid: oVoc.vid, again: false} }, ShowMiniHint);
			}
		});

		if (parseInt($('#nknowcount').html()) == 0) {
			$('#nknow').hide();
			$('#hknow').hide();
		}
		else {
			$('#nknow').show();
			$('#hknow').show();
		}

		$('#nknow').bind("click", ShowNKnow);
		$('#hknow').bind("click", ShowHKnow);
		$('#alldict').bind("click", ShowAllDict);
	}
);

function ShowHKnow() {
	$.each($('#mastery a'), function () {
		$(this).removeClass('current');
	});
	$(this).addClass('current');
	$.each($('#ullist li'), function () {
		if ($(this).attr('class') == '' || $(this).attr('class') == 'last') {
			$(this).show();
		}
		else {
			$(this).hide();
		}
	});
}

function ShowNKnow() {
	$.each($('#mastery a'), function () {
		$(this).removeClass('current');
	});
	$(this).addClass('current');
	$.each($('#ullist li'), function () {
		if ($(this).attr('class') == '' || $(this).attr('class') == 'last') {
			$(this).hide();
		}
		else {
			$(this).show();
		}
	});
}

function ShowAllDict() {
	$.each($('#mastery a'), function () {
		$(this).removeClass('current');
	});
	$(this).addClass('current');
	$.each($('#ullist li'), function () {
		$(this).show();
	});
}


var dictlist = [];
function BuildList() {
	var length = jsondata.dicts.length;

	for (var i = 0; i < length; i++) {
		var dict = jsondata.dicts[i];
		dictlist[i] = length - i - 1;
		BuildDict(dict, i, jsondata.vid);
	}
	$("#ullist li:last-child").addClass("last");
}

function BuildDict(dict, num, vid) {
	var sb = new StringBuffer();
	var did = dict.id;
	var know = $.inArray(did, Aknow);
	var collect = $.inArray(did, ACollect);
	var Spell = dict.spell;
	var Pronunciation = dict.pron;
	var ListIndex = dict.li;

	sb.Append('<li ' + (know >= 0 ? 'class="know"' : '') + ' id="li_' + did + '">');

	sb.Append('<div style="position:relative;">');
	sb.Append('<div class="dict">');

	sb.Append('<label class="num"> ' + (num + 1) + '. </label>');

	sb.Append('<span class="spell">' + Spell + '</span>');

	if (Pronunciation != "") {
		sb.Append('<span style="visibility:hidden"> … </span>');

		sb.Append('<span class="pron">' + Pronunciation.replace(/\|/gim, '<img border="0" src="/Common/images/compart.png" class="compart"/>') + '</span>');
	}

	if (Spell.indexOf(" ") == -1 && Spell.indexOf("…") == -1) {
		sb.Append("<span class=\"\" style=\"visibility:hidden\"> … </span>");
	}
	sb.Append("</div>");
	sb.Append('<span class="dict-act">');
	sb.Append('&nbsp;<a id="see_' + did + '">看</a>');
	sb.Append('&nbsp;<a id="guess_' + did + '">猜</a>');
	if (know >= 0) {
		sb.Append('&nbsp;<a id="know_' + did + '">显</a>');
	}
	else {
		sb.Append('&nbsp;<a id="know_' + did + '">隐</a>');
	}
	sb.Append("</span>");
	sb.Append("</div>");

	sb.Append('<div id="div_' + did + '" class="ph hide">' + GetPh(dict.ph1) + '</div>');

	sb.Append('<div id="t_' + did + '" class="test hide"></div>');
	sb.Append("</li>");

	$('#ullist').append(sb.toString());

	$('#know_' + did).bind("click", { fun: Know, title: "操作成功", argus: { did: did, num: num, again: false} }, ShowMiniHint);
	$('#guess_' + did).bind("click", { vid: vid, did: did, num: num, again: false }, Guess);
	$('#see_' + did).bind("click", { vid: vid, did: did, num: num, again: false }, Open);
}

function GetPh(x) {
	x = BlodPh(x);
	x = x.replace(/\[en\](.*?)\[\/en\]/gim, '<div style="font-size:14px;">$1</div>')
	x = x.replace(/\[cn\](.*?)\[\/cn\]/gim, "<div>$1</div>");
	return x;
}


function Know(argus) {
	if (userid == '') return;

	var did = argus.did;
	var again = argus.again;

	log(did);
	$.ajax({
		url: '/Submit/submit.ashx?page=voc&action=005&did=' + did + '&rnd=' + Math.random(),
		type: 'GET',
		timeout: 5000,
		dataType: "json",
		error: function () {
			AddMiniHint('操作失败，<a class="action" onclick="Know({did:' + did + ',again:true})">请重试</a>');
		},
		success: function (json) {
			if (json.code == 0) {
				if ($('#li_' + did).hasClass('know')) {
					$('#li_' + did).removeClass('know');
				}
				else {
					$('#li_' + did).addClass('know');
				}

				AddMiniHint('操作成功！');
				if ($('#know_' + did).html() == '隐') {
					$('#know_' + did).html('显');
					$('#nknowcount').html(parseInt($('#nknowcount').html()) + 1);
					$('#hknowcount').html(parseInt($('#hknowcount').html()) - 1);
				}
				else {
					$('#know_' + did).html('隐');
					$('#nknowcount').html(parseInt($('#nknowcount').html()) - 1);
					$('#hknowcount').html(parseInt($('#hknowcount').html()) + 1);
				}

				if (parseInt($('#nknowcount').html()) == 0) {
					$('#nknow').fadeOut();
					$('#hknow').fadeOut();
					$('#alldict').click();
				}
				else {
					$('#nknow').fadeIn();
					$('#hknow').fadeIn();
				}

				HideMiniPop(1000);
			}
			else {
				AddMiniHint('操作失败，<a class="action" onclick="Know({did:' + did + ',again:true})">请重试</a>');
			}
		}
	});
}

function Open(e) {
	var vid = e.data.vid;
	var did = e.data.did;
	var num = e.data.num;
	var event = e;
	var x = jsondata.dicts[num].ph1;
	$('#div_' + did).toggle();
	$('#t_' + did).hide();
	$('#t_' + did).html('');

	if ($('#div_' + did).html() == '') {
		if (x != '') {
			x = BlodPh(x);
			x = x.replace(/\[en\](.*?)\[\/en\]/gim, function (a, b) {
				b = stripSpace(b);
				var d = b.split(' '), m = '';

				for (var i = 0; i < d.length; i++) {
					var di = d[i];

					if (di == 'i.e.') {
						di = di;
					}
					else {
						di = di.replace(/^(\,|，|\.|。|、|\?|？|\"|“|”|\'|‘|’)?(.*?)(\,|，|\.|。|、|\?|？|\"|“|”|\'|‘|’)?$/g, function (a, b, c, d) {
							if (typeof b == 'undefined') b = '';
							if (typeof d == 'undefined') d = '';
							return b + ' <a title="" target="_blank" href="/Dict.aspx?w=' + c + '">' + c + '</a> ' + d;

						});
					}

					m += di;
				}
				return '<div style="font-size:14px;">' + m + '</div>';
			});
			x = x.replace(/\[cn\](.*?)\[\/cn\]/gim, "<div>$1</div>");

		}
		else {
			if (oVoc.admin == false) {
				x = '<div><a href="user.aspx?uid=' + oVoc.adminid + '">' + oVoc.adminname + '</a>&nbsp;&nbsp;还未编辑完成，请期待吧</div>';
			}
			else {
				x = '<div><a href="/dict.aspx?i=' + did + '">编辑</a></div>';
			}
		}

		if (oVoc.status >= 0) {

			x += "<div><textarea id=\"cmt_" + did + "\" onclick=\"Cmt(" + did + "," + num + ");\" class=\"cmt\">" + cmttxt + "</textarea>";
			x += '<div id="btndiv_' + did + '" class="hide" style="margin-top:3px;"><input type="button" value="确定" class="btn" id="btn_' + did + '" />&nbsp;&nbsp;<a href="javascript:void(0)" class="anb" onclick="CancelCmt(' + did + ',' + num + ');" id="cancel_' + did + '">取消</a>';
			x += '&nbsp;&nbsp;(你还可输入<span id="rlen_' + did + '">250</span>字)&nbsp;&nbsp;</div>';
			x += "</div><div id='ch_" + did + "' class='comments'></div>";
			$('#div_' + did).html(x);

			GetComment(did, false);

			$('#btn_' + did).bind("click", { fun: Comment, title: "操作成功", argus: { did: did, again: false} }, ShowMiniHint);
			$('#cmt_' + did).bind('propertychange', { len: 250, did: did }, CheckLen);
			$('#cmt_' + did).bind('input', { len: 250, did: did }, CheckLen);

		}
		else {
			$('#div_' + did).html(x);
		}
	}

	event.stopPropagation();
}

function GetComment(did, again) {
	$.ajax({
		url: '/Submit/submit.ashx?page=voc&action=007&did=' + did + '&rnd=' + Math.random(),
		type: 'GET',
		timeout: 5000,
		dataType: "json",
		error: function () {
			if (again) {
				$('#ch_' + did).html('');
			}
			else {
				$('#ch_' + did).html('加载失败，<a class="action" onclick="GetComment(' + did + ',true)">请重试</a>');
			}
		},
		success: function (json) {
			if (json.code >= 0) {
				var obj = json.obj;
				var h = obj.length;

				for (var i = 0; i < h; i++) {
					var csb = new StringBuffer();
					var cid = obj[i].cid;
					var uid = obj[i].uid;
					var name = obj[i].name;

					csb.Append('<div id="ct_' + cid + '" class="item  ' + (i == h - 1 ? 'last' : '') + ' clearfix"><div class="relative"><a class="avatar" target="_blank" href=""><img src="' + obj[i].img + '" alt=""></a>');
					csb.Append('<div class="info"><a href="/user.aspx?uid=' + uid + '" target="_blank">' + obj[i].name + '</a>&nbsp;&nbsp;<span>' + obj[i].content + '</span></div>');
					csb.Append('<div class="replay-action" data-id="' + cid + '">');

					if (userid == obj[i].uid) {
						csb.Append('<a id="ct_' + cid + '_o" class="action">删除</a>');
					}
					else {
						csb.Append('<a id="ct_' + cid + '_o" class="action">屏蔽</a>');
					}

					csb.Append('<a class="action">回复</a></div></div>');
					csb.Append('<div class="review hide" id="ct_' + cid + '_review"></div></div>');

					$('#ch_' + did).append(csb.toString());

					$.each($('#ct_' + cid + ' .action'), function () {
						var txt = $(this).text();
						if (txt == '删除') {
							$(this).bind("click", { fun: DeleteComment, title: "确认删除此分享？", argus: { cid: cid, did: did, again: false} }, ShowMiniPop);
						}
						else if (txt == '屏蔽') {
							$(this).bind("click", { fun: ScreenComment, title: "确认屏蔽此分享？", argus: { cid: cid, did: did, again: false} }, ShowMiniPop);
						}
						else if (txt == '回复') {
							$(this).bind("click", { cid: cid, did: did, uid: uid, name: name }, ReviewClick);
						}
					});
				}
				$('#ch_' + did).append('<span id="rd_' + did + '">' + json.code + '</span>分享&nbsp;&nbsp;<a target="_blank" href="/dict.aspx?i=' + did + '">浏览全部</a>');
			}
			else {
				if (again) {
					$('#ch_' + did).html('');
				}
				else {
					$('#ch_' + did).html('加载失败，<a class="action" onclick="GetComment(' + did + ',true)">请重试</a>');
				}
			}
		}
	});
}

function ReviewClick(e) {
	var data = e.data;
	Cmt(data.did, 0);
	if (data.uid == userid) {
		$('#cmt_' + data.did).val('回复@' + data.name + ' :');
	}
	$('#cmt_' + data.did).focus();
}

function ScreenComment(argus) {
	var cid = argus.data.cid;
	var again = argus.data.again;
	var did = argus.data.did;

	if (userid == '') {
		AddMiniHint('请先登录！');
		HideMiniPop(1500);
		return;
	}

	$.ajax({
		url: '/Submit/submit.ashx?page=voc&action=002&cid=' + cid + '&rnd=' + Math.random(),
		type: 'GET',
		timeout: 5000,
		dataType: "json",
		error: function () {
			AddMiniHint('屏蔽失败，<a class="action" onclick="ScreenComment({data:{cid:' + cid + ',did:' + did + ',again:true}})">请重试</a>');
		},
		success: function (json) {
			if (json.code == 0) {
				$('#ct_' + cid).fadeOut(1000);
				$('#rd_' + did).html(parseInt($('#rd_' + did).html()) - 1);
				HideMiniPop();
			}
			else {
				AddMiniHint('屏蔽失败，<a class="action" onclick="ScreenComment({data:{cid:' + cid + ',did:' + did + ',again:true}})">请重试</a>');
			}
		}
	});
}

function DeleteComment(argus) {
	var cid = argus.data.cid;
	var again = argus.data.again;
	var did = argus.data.did;

	if (userid == '') {
		AddMiniHint('请先登录！');
		HideMiniPop(1500);
		return;
	}
	$.ajax({
		url: '/Submit/submit.ashx?page=voc&action=001&cid=' + cid + '&rnd=' + Math.random(),
		type: 'GET',
		timeout: 5000,
		dataType: "json",
		error: function () {
			AddMiniHint('删除失败，<a class="action" onclick="DeleteComment({data:{cid:' + cid + ',did:' + did + ',again:true}})">请重试</a>');
		},
		success: function (json) {
			if (json.code == 0) {
				$('#ct_' + cid).fadeOut(1000);
				$('#rd_' + did).html(parseInt($('#rd_' + did).html()) - 1);
				HideMiniPop();
			}
			else {
				AddMiniHint('删除失败，<a class="action" onclick="DeleteComment({data:{cid:' + cid + ',did:' + did + ',again:true}})">请重试</a>');
			}
		}
	});
}

function CheckLen(e) {
	var str = $(this).val();
	var len = str.replace(/[^\x00-\xff]/g, "**").length;
	$('#rlen_' + e.data.did).text(parseInt(e.data.len) - len)
}

function Comment(argus) {
	var did = argus.did;
	var again = argus.again;

	$.ajax({
		url: '/Submit/submit.ashx?page=voc&action=008&did=' + did + '&rnd=' + Math.random(),
		type: 'POST',
		timeout: 5000,
		dataType: "json",
		data: { 'cmt': $('#cmt_' + did).val() },
		error: function () {
			AddMiniHint('操作失败，<a class="action" onclick="Comment({did:' + did + ',again:true})">请重试</a>');
		},
		success: function (json) {
			if (json.code == 0) {
				var obj = json.obj;
				var csb = new StringBuffer();
				var cid = obj.cid;
				var uid = obj.uid;
				var name = obj.name;

				AddMiniHint('操作成功！');

				$('#cmt_' + did).val('')

				csb.Append('<div id="ct_' + cid + '" class="item clearfix"><div class="relative"><a class="avatar" target="_blank" href=""><img src="' + obj.img + '" alt=""></a>');
				csb.Append('<div class="info"><a href="/user.aspx?uid=' + uid + '" target="_blank">' + obj.name + '</a>&nbsp;&nbsp;<span>' + obj.content + '</span></div>');
				csb.Append('<div class="replay-action" data-id="' + cid + '">');

				if (userid == obj.uid) {
					csb.Append('<a id="ct_' + cid + '_o" class="action">删除</a>');
				}
				else {
					csb.Append('<a id="ct_' + cid + '_o" class="action">屏蔽</a>');
				}

				csb.Append('<a class="action">回复</a></div></div>');
				csb.Append('<div class="review hide" id="ct_' + cid + '_review"></div></div>');



				if ($('#ch_' + did).html() == '') {
					$('#ch_' + did).append(csb.toString());
				}
				else {
					$(csb.toString()).insertBefore($('#ch_' + did + '').children().eq(0));
				}

				$('#rd_' + did).html(parseInt($('#rd_' + did).html()) + 1);

				$.each($('#ct_' + cid + ' .action'), function () {
					var txt = $(this).text();
					if (txt == '删除') {
						$(this).bind("click", { fun: DeleteComment, title: "确认删除此评论？", argus: { cid: cid, did: did, again: false} }, ShowMiniPop);
					}
					else if (txt == '屏蔽') {
						$(this).bind("click", { fun: ScreenComment, title: "确认屏蔽此评论？", argus: { cid: cid, did: did, again: false} }, ShowMiniPop);
					}
					else if (txt == '回复') {
						$(this).bind("click", { cid: cid, did: did, uid: uid, name: name }, ReviewClick);
					}
				});

				HideMiniPop(1000);
			}
			else {
				AddMiniHint('操作失败，<a class="action" onclick="Comment({did:' + did + ',again:true})">请重试</a>');

			}
		}
	});
}

//评论框获得焦点执行操作
function Cmt(id, mum) {
	var cmt = $('#cmt_' + id);
	if (cmt.val() == cmttxt) {
		cmt.val('');
		cmt.css({ 'color': '#000', 'height': '45px' });
		$('#btndiv_' + id).show();
	}
}
//取消评论执行操作
function CancelCmt(id, mum) {
	var cmt = $('#cmt_' + id);
	cmt.val(cmttxt);
	cmt.css({ 'color': '#E3E3E3', 'height': '18px' });
	$('#btndiv_' + id).hide();
}

//猜猜
function Guess(e) {
	log('guess');
	var vid = e.data.vid;
	var did = e.data.did;
	var num = e.data.num;
	var event = e;

	if ($('#t_' + did).html() != '') {
		$('#t_' + did).html('');
		$('#t_' + did).hide();
		return;
	}
	else {
		BuildTest(did, num, true, '');
		$('#div_' + did).hide();
	}
    event.stopPropagation();
}

function BuildTest(did, num, t, pre) {
	if (pre != '') pre = pre + '-';
	var d = GuessData.dicts[num];
	if (d == null) {
		return;
	}
	var ph = d.ph;
	var c = [-1, -1, -1, -1];
	var r = Math.floor(Math.random() * 4);
	c[r] = num;

	var sb = new StringBuffer();
	sb.Append('<div class="choice">');

	for (var i = 0; i < c.length; i++) {
		var cc;
		if (i != r) {
			var rr = RdmChoice(num, c);
			var dd = GuessData.dicts[rr];
			c[i] = rr;
			cc = { 'did': dd.id, 'spell': dd.spell, 'ph': dd.ph, 'num': rr };
		}
		else {
			cc = { 'did': did, 'spell': d.spell, 'ph': ph, 'num': num };
		}
		sb.Append(BuildChoice(did, i + 1, cc, r + 1, t, pre));
	}
	$('#' + pre + 't_' + did).show();
	$('#' + pre + 't_' + did).html(sb.toString());
}

function BuildChoice(did, i, c, a, t, pre) {
	var sb = new StringBuffer();

	var inputid = 'input_' + i;
	sb.Append('<div class="radio" id="' + pre + 'r_' + did + '_' + i + '">');
	sb.Append('     <div class="abcd">');

	sb.Append('         <input type="radio" id="' + pre + '' + did + '_' + inputid + '" name="radios_' + pre + '' + did + '" onclick="RadioClick(' + (i) + ',' + (a) + ',' + did + ',' + c.did + ',' + c.num + ',' + !t + ',\'' + pre + 'd_' + did + '\')" value="' + (i) + '" />');

	sb.Append('         <span>' + Num2ABC(i) + '.</span>');

	sb.Append('     </div>');
	sb.Append('     <div class="content"><label id="' + pre + 'l_' + did + '_' + inputid + '" for="' + pre + '' + did + '_' + inputid + '">');
	if (t == true)
		sb.Append(c.ph);
	else
		sb.Append(c.spell);

	sb.Append('         <span class="judge" id="' + pre + 'j_' + did + '_' + i + '"></span></label></div>');
	sb.Append('     <div style="clear:both;"></div>');
	sb.Append('     <div id="' + pre + 'd_' + did + '-t_' + c.did + '" class="' + (t == true ? 'f' : 't') + 'choice hide"></div>');
	sb.Append(' </div>');

	return sb.toString();
}

function RadioClick(i, a, did, cdid, num, t, pre) {
	var prepre = '';
	if (pre.indexOf('-') != -1) {
		prepre = pre.substr(0, pre.lastIndexOf('-')) + '-';
	}
	if (i == a) {
		$('#' + prepre + 'j_' + did + '_' + i + '').html('<img src="/Common/images/t.png" />');
		$('#' + prepre + 't_' + did).fadeOut(1200, function () {
			if (prepre != '') {
				$('#' + prepre + 't_' + did).parent().removeClass('current');
			}
			$('#' + prepre + 't_' + did).html('');
		});
	}
	else {
		$('#' + prepre + 'j_' + did + '_' + i + '').html('<img src="/Common/images/f.png" />');
		if ($('#' + pre + '-t_' + cdid).html() != '') {
			$('#' + pre + '-t_' + cdid).html('');
			$('#' + pre + '-t_' + cdid).hide();
			$('#' + prepre + 'r_' + did + '_' + i).removeClass('current');
		}
		else {
			if (t == false) {
				$('#' + prepre + 'r_' + did + '_' + i).addClass('current');
			}
			BuildTest(cdid, num, t, pre);
		}
	}
}

function Follow(argus) {
	if (userid == '') return;

	var vid = argus.vid;
	var again = argus.again;

	$.ajax({
		url: '/Submit/submit.ashx?page=list&action=012&vid=' + vid + '&rnd=' + Math.random(),
		type: 'GET',
		timeout: 5000,
		dataType: "json",
		error: function () {
			AddMiniHint('操作失败，<a class="action" onclick="Follow({vid:' + vid + ',again:true})">请重试</a>');
		},
		success: function (json) {
			if (json.code == 0) {
				AddMiniHint('操作成功！');
				var st = $('#control_panel > a').eq(1);
				if (st.text().trim() == '关注') {
					st.html('已关注');
					st.attr('title', '点击取消关注');
					st.removeClass('follow').addClass('followed');
				}
				else {
					st.html('关注');
					st.removeClass('followed').addClass('follow');
				}

				HideMiniPop(1000);
			}
			else {
				AddMiniHint('操作失败，<a class="action" onclick="Follow({vid:' + vid + ',again:true})">请重试</a>');

			}
		}
	});
}

function RdmChoice(num, c) {
	var r = Math.floor(Math.random() * (GuessData.dicts.length - 0) + 0);
	if (r != num) {
		var l = c.length, m;
		for (var i = 0; i < c.length; i++) {
			if (r == c[i]) {
				return RdmChoice(num, c);
			}
		}
		return r;
	}
	return RdmChoice(num, c);
}

